function dateStrToTimestamp(str) {
    var timestamp = Date.parse(new Date(str));
    return timestamp / 1000;
}

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

function delImg(id) {
    $('#' + id + ' .delbtn').hide();
    var path = $('#val_' + id).val();
    if (path) {
        $.post('/acp/common/deletefile', {'file': path}, function (resp) {
            if (resp.code != 200) {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
            }
            $('#' + id).remove();
        });
    } else {
        $.scojs_message('尚未上传完毕', $.scojs_message.TYPE_ERROR);
    }
}

$(function () {
    $('form').find('.submit').click(function (e) {
        $(this).addClass('disabled');
        $('form').find('.submit').html('请求中<i class="fa fa-fw fa-upload"></i>');
        $.post($('form').attr('action'), $('form').serialize(), function (resp) {
            if (resp.code == 200) {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_OK);
                if ($('form').data('redirect')) {
                    setTimeout(function () {
                        location.href = $('form').data('redirect');
                    }, 500);
                }else{
                    setTimeout(function () {
                        history.back();
                    }, 500);
                }
            } else {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
                $('form').find('.submit').removeClass('disabled');
            }
        });
        return false;
    });

    $('.delete').click(function () {
        var remoteUrl = $(this).data('url');
        var lineDom = $(this).parent().parent();
        $(this).scojs_confirm({
            content: '确定执行操作?',
            target: '#' + uuid(),
            keyboard: true,
            action: function () {
                $.post(remoteUrl, function (resp) {
                    if (resp.code == 200) {
                        lineDom.remove();
                    } else {
                        $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
                    }
                });
            }
        });
    });

    $('.update').click(function () {
        var updateUrl = $(this).data('url');

        $(this).scojs_confirm({
            content: '确定修改?',
            target: '#' + uuid(),
            action: function () {
                $.post(updateUrl, function (resp) {
                    if (resp.code == 200) {
                        location.reload();
                    } else {
                        $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
                    }
                });
            }
        });
    });

    $('.switch').click(function () {
        var remoteUrl = $(this).data('url');
        var btn = $(this);
        $.post(remoteUrl, function (resp) {
            if (resp.code == 200) {
                btn.text(resp.data.tip);
                switch (resp.data.status) {
                    case '1':
                        btn.removeClass('btn-success');
                        btn.addClass('btn-danger');
                        break;
                    case '0':
                        btn.addClass('btn-success');
                        btn.removeClass('btn-danger');
                        break;
                }
                location.reload();
            } else {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
            }
        });

    });

    $('.button-request').click(function () {
        var remoteUrl = $(this).data('url');
        var postData = $(this).data('values');
        var confirm = $(this).scojs_confirm({
            content: '确定操作?',
            target: '#' + uuid(),
            keyboard: true,
            action: function () {
                $.post(remoteUrl, postData, function (resp) {
                    if (resp.code == 200) {
                        $.scojs_message(resp.msg, $.scojs_message.TYPE_OK);
                    } else {
                        $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
                    }
                });
            }
        });
    });

    $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
        checkboxClass: 'icheckbox_minimal-red',
        radioClass: 'iradio_minimal-red'
    });

    var uploader = [];
    var multiUploader = [];
    $('.uploadimg').each(function (idx) {
        var filePicker = $(this).find('.filepicker');
        var imgList = $(this).find('.filelist');
        var fileName = filePicker.data('name');

        var pic = filePicker.data('pic');
        var weixin = filePicker.data('weixin') ? filePicker.data('weixin') : '';
        var appid = filePicker.data('appid') ? filePicker.data('appid') : '';
        if (pic) {
            var tmpID = "tmp_" + Math.round(Math.random() * 10000);
            var $li = $(
                '<div id="' + tmpID + '" class="file-item thumbnail col-xs-6 col-md-3"><span class="btn btn-sm btn-danger" style="z-index:11; position: absolute;" onclick="delImg(\'' + tmpID + '\')"><i class="fa fa-trash"></i></span>' +
                '<img src="' + pic + '" style="height: 160px;">' +
                '<input id="val_' + tmpID + '" name="' + fileName + '" type="hidden" value="' + pic + '" />' +
                '</div>'
                ),
                $img = $li.find('img');

            // $list为容器jQuery实例
            imgList.append($li);
        }


        uploader[idx] = WebUploader.create({
            pick: {
                id: filePicker,
                multiple: false
            },
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: 'https://cdn.staticfile.org/webuploader/0.1.5/Uploader.swf',
            // 文件接收服务端。
            server: UPLOAD_URL + '?weixin=' + weixin + '&appid=' + appid,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif'
            },
            fileNumLimit: 1
        })

        uploader[idx].on('fileQueued', function (file) {
            imgList.empty();
            var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail col-xs-6 col-md-3"><span class="btn btn-sm btn-danger delbtn hide" style="z-index:11; position: absolute;" onclick="delImg(\'' + file.id + '\')"><i class="fa fa-trash"></i></span>' +
                '<img>' +
                '<input id="val_' + file.id + '" name="' + fileName + '" type="hidden" value="" />' +
                '</div>'
                ),
                $img = $li.find('img');

            // $list为容器jQuery实例
            imgList.append($li);

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100

            uploader[idx].makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
                $img.attr('src', src);
            }, 160, 160);
        });

        uploader[idx].on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo($li).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css('width', percentage * 100 + '%');
        });

        uploader[idx].on('uploadSuccess', function (file, resp) {
            if (resp.code == 200) {
                $('#' + file.id).addClass('upload-state-done');
                $('#' + file.id + ' .delbtn').removeClass('hide').show();
                $('#val_' + file.id).val(resp.data.path);
            } else {
                var $li = $('#' + file.id), $error = $li.find('div.error');

                // 避免重复创建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
                $error.text(resp.msg);
            }
            $('#' + file.id + ' .progress').remove();
        });


        uploader[idx].on('uploadError', function (file) {
            var $li = $('#' + file.id), $error = $li.find('div.error');

            // 避免重复创建
            if (!$error.length) {
                $error = $('<div class="error"></div>').appendTo($li);
            }

            $error.text('上传失败');
        });

        uploader[idx].on('uploadFinished', function (file) {
            uploader[idx].reset();
        });
    });


    $('.muluploadimg').each(function (idx) {
        var filePicker = $(this).find('.filepicker');
        var imgList = $(this).find('.filelist');
        var fileName = filePicker.data('name');

        var pic = filePicker.data('pic');
        var weixin = filePicker.data('weixin') ? filePicker.data('weixin') : '';
        var appid = filePicker.data('appid') ? filePicker.data('appid') : '';
        if (pic) {
            var pics = pic.split(';');
            var picsLen = pics.length;
            for (var i = 0; i < picsLen; i++) {
                var tmpID = "tmp_" + Math.round(Math.random() * 10000);
                var $li = $(
                    '<div id="' + tmpID + '" class="file-item thumbnail col-xs-6 col-md-3"><span class="btn btn-sm btn-danger" style="z-index:11; position: absolute;" onclick="delImg(\'' + tmpID + '\')"><i class="fa fa-trash"></i></span>' +
                    '<img src="' + pics[i] + '" style="height: 160px;">' +
                    '<input id="val_' + tmpID + '" name="' + fileName + '[]" type="hidden" value="' + pics[i] + '" />' +
                    '</div>'
                    ),
                    $img = $li.find('img');

                // $list为容器jQuery实例
                imgList.append($li);
            }
        }

        multiUploader[idx] = WebUploader.create({
            pick: {
                id: filePicker,
                multiple: true
            },
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: 'https://cdn.staticfile.org/webuploader/0.1.5/Uploader.swf',
            // 文件接收服务端。
            server: UPLOAD_URL + '?weixin=' + weixin + '&appid=' + appid,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif'
            },
            duplicate: false,
            fileNumLimit: 50
        })

        multiUploader[idx].on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo($li).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css('width', percentage * 100 + '%');
        });

        multiUploader[idx].on('fileQueued', function (file) {
            var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail col-xs-6 col-md-3"><span class="btn btn-sm btn-danger delbtn hide" style="z-index:11; position: absolute;" onclick="delImg(\'' + file.id + '\')"><i class="fa fa-trash"></i></span>' +
                '<img>' +
                '<input id="val_' + file.id + '" name="' + fileName + '[]" type="hidden" value="" />' +
                '</div>'
                ),
                $img = $li.find('img');

            // $list为容器jQuery实例
            imgList.append($li);

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            multiUploader[idx].makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
                $img.attr('src', src);
            }, 160, 160);
        });

        multiUploader[idx].on('uploadSuccess', function (file, resp) {
            if (resp.code == 200) {
                $('#' + file.id).addClass('upload-state-done');
                $('#' + file.id + ' .delbtn').removeClass('hide').show();
                $('#' + file.id + ' .delbtn').show();
                $('#val_' + file.id).val(resp.data.path);
            } else {
                var $li = $('#' + file.id), $error = $li.find('div.error');

                // 避免重复创建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
                $error.text(resp.msg);
            }
            $('#' + file.id + ' .progress').remove();
        });


        multiUploader[idx].on('uploadError', function (file) {
            var $li = $('#' + file.id), $error = $li.find('div.error');

            // 避免重复创建
            if (!$error.length) {
                $error = $('<div class="error"></div>').appendTo($li);
            }

            $error.text('上传失败');
        });

        multiUploader[idx].on('uploadFinished', function (file) {
            multiUploader[idx].reset();
        });
    });

    $('.sortorder').change(function () {
        var id = $(this).data('id');
        $.post('sort', {'id': id, 'sort': $(this).val()}, function (resp) {
            if (resp.code == 200) {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_OK);
            } else {
                $.scojs_message(resp.msg, $.scojs_message.TYPE_ERROR);
            }
        });
    });
});